'''
Created on May 5, 2011

@author: saierlab
'''

import urllib2
    
def byTcid(tcid, pretty=False):

    ''' Returns sequence(s) specified by given TCID.

    tcid = up to five character string delineated by "." (see tcdb.org)

    pretty = (boolean) output <br /> instead of newlines, wrap sequences to 80-long
    '''

    tcidarray = tcid.split(".")
    if (tcidarray.__len__() > 5) :
        raise Exception("TC IDs cannot be greater than five digits in length.")
    elif (tcidarray.__len__() <= 1) :
        raise Exception("TC IDs cannot be less than or one number.")
    return apiCall("tcid="+tcid, pretty)

def apiCall(string, pretty=False):

    ''' Appends the given string to a tcdb api call.

    string = of the form "variable=value"

    pretty = use <br /> instead of \n and wrap sequences at 80 characters on output
    '''
    
    if (pretty):
        string = string+"&pretty"
    tcdb_handle = urllib2.urlopen("http://www.tcdb.org/api.php?" + string)
    return tcdb_handle.read()

def allFromTCDB(pretty=False):

    ''' Returns all sequences from TCDB (database dump). WARNING: please do not use
    this method in loops or other repeated calls; store the return for later use!

    pretty = use <br /> instead of \n and wrap sequences at 80 char on output
    '''

    return apiCall("tcid=all", pretty)

def toFile(filename, info, overwrite):
    '''Writes info a filename of your choosing.
    filename = take a guess
    info = likewise
    overwrite = specify whether to overwrite or append
    '''
    if overwrite:
        outfile = open(filename, 'w')
    else:
        outfile = open(filename, 'a')
        
    outfile.write(info)
    outfile.close()
    